<?php
/**
 * Created by PhpStorm.
 * User: wx:wenyi2048
 * Date: 2022/3/19 0019
 * Time: 16:45
 */

namespace app\common\service;


use app\common\model\mk\Invoices;
use think\Db;
use think\Exception;

class InvoicesService extends Service
{
    protected $tableName = 'sms_mk_invoices';

    protected $userAdminId;//店铺管理员id

    protected $store = [];



    public function dbQuery(){
        $this->db->alias('i')
            ->join('sms_mk_orders o','o.id = i.sms_order_id')
            ->join('sms_mk_stores s','o.store_id = s.id','left')
            ->order('i.id','desc')
            ->field('i.*,o.number,o.total_fee,o.id as order_id,s.thumb');
    }

    public function datalist()
    {
        $this->setDb('invoices_view');
        $this->db->where('sms_users_id','=',$this->param['sms_users_id']);
        if(@$this->param['state']) $this->db->where('state','=',$this->param['state']);
        return parent::datalist(); // TODO: Change the autogenerated stub
    }

    /**
     * @param $view
     * @param $params
     * @param int $isdelete  返回全部商品分页
     */
    public function searchPage(&$view,$param,$isdelete = 0){
        $this->dbQuery();
        $storeId = $this->checkStoreSelect(@$param['store_id']);
        if($storeId) $this->db->where('o.store_id','=',$storeId);
        $this->pageList($view,$param);
    }

    public function delete(){
        $invoices = Db::table('sms_mk_invoices')->where('sms_order_id','=',$this->param['sms_order_id'])->find();
        if(@$invoices['state'] == 'finished')
            throw  new Exception('该订单已经开票，不得取消');
        return $this->db->where('id','=',$this->param['id'])
            ->where('sms_users_id','=',$this->param['sms_users_id'])
            ->delete();
    }

    public function billing($id){
        return $this->db->where('id','=',$id)->update(['state'=>'finished']);
    }

    public function add()
    {
        $order = Db::table('sms_mk_orders')->where('id','=',$this->param['sms_order_id'])->find();
        if($order['state']=='require' || $order['state'] == 'await')
            throw  new Exception('订单状态不对');
        if(Db::table('sms_mk_invoices')->where('sms_order_id','=',$this->param['sms_order_id'])->find())
            throw  new Exception('该订单不能重复索要发票');
        $this->param['create_time'] = (string)time();
        return parent::add(); // TODO: Change the autogenerated stub
    }
}